package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CheckOverListOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;

import org.json.JSONException;

import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/2/7 15:11
 */
public class CheckOverNewFragment extends Fragment {
  protected static final String EXTRA_STATUS =
      "com.isunland.managesystem.ui.CheckOverNewFragment.EXTRA_STATUS";
  protected static String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.CheckOverNewFragment.EXTRA_CONTENT";
  protected static String EXTRA_PID = "com.isunland.managesystem.ui.CheckOverNewFragment.EXTRA_PID";

  private CheckOverListOriginal.CheckOverListContent mcontent;
  private BaseVolleyActivity mActivity;
  protected static final int ADD = 1;
  protected static final int EDIT = 2;
  protected static final int CHECK = 3;// 审核中或审核通过

  protected static final int REQUEST_ACTUAL_DATE_END = 1;
  protected static final int REQUEST_ACTUAL_DATE_START = 2;
  public static final int REQUEST_DELETE = 3;
  public static final int REQUEST_SUBMIT = 4;
  protected String mPid;
  protected String mId;
  protected String mDataStatus;
  protected int mMenuType;

  private EditText mEtReason;
  private TextView mTvActualStartTime;
  private TextView mTvActualEndTime;
  private EditText mEtActualHours;

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      if (NavUtils.getParentActivityName(getActivity()) != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
      }
      actionBar.setTitle(R.string.requisitionover);
    }

    mcontent =
        (CheckOverListOriginal.CheckOverListContent) getArguments().getSerializable(EXTRA_CONTENT);
    mDataStatus = (String) getArguments().getSerializable(EXTRA_STATUS);
    mPid = (String) getArguments().getSerializable(EXTRA_PID);
    if (null == mcontent) {
      //添加
      mMenuType = ADD;
    } else {
      if (null != mDataStatus && (mDataStatus.equalsIgnoreCase("new")
          || mDataStatus.equalsIgnoreCase("abort"))) {
        //草稿终止状态可以修改保存和删除
        mMenuType = EDIT;
      }
      if (null != mDataStatus && (mDataStatus.equalsIgnoreCase("checkPass")
          || mDataStatus.equalsIgnoreCase("waitCheck"))) {
        //审核通过或审核中不能编辑
        mMenuType = CHECK;
      }
    }

    super.onCreate(savedInstanceState);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_save_delete, menu);
    switch (mMenuType) {
      case ADD:
        //添加时没有删除,只可以保存
        menu.getItem(1).setVisible(false).setEnabled(false);
        break;
      case CHECK:
        //审核中或审核通过时不可编辑
        menu.getItem(0).setVisible(false).setEnabled(false);
        menu.getItem(1).setVisible(false).setEnabled(false);
        break;
      case EDIT:
        //草稿和审核通过可编辑

        break;
      default:
        break;
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        return true;
      case R.id.menu_item_save:
        //保存
        if (isCorrectInput()) {
          volleyPostSave();
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        DialogFragment dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);
        FragmentManager fm = getActivity().getSupportFragmentManager();
        dialog.setTargetFragment(this, REQUEST_DELETE);
        dialog.show(fm, "");
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_check_over, container, false);
    findViews(view);
    initData();
    return view;
  }

  private void findViews(View v) {

    mEtReason = (EditText) v.findViewById(R.id.et_overTimeReason_checkOver);
    mTvActualStartTime = (TextView) v.findViewById(R.id.tv_actualBeginTime_checkOver);
    mTvActualEndTime = (TextView) v.findViewById(R.id.tv_actualEndTime_checkOver);
    mEtActualHours = (EditText) v.findViewById(R.id.et_actualOverTimeHours_checkOver);

    //开始时间
    mTvActualStartTime.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {

        showDialog(mTvActualStartTime.getText().toString().trim(), R.string.chooseTime,
            REQUEST_ACTUAL_DATE_START);
      }
    });
    //结束时间
    mTvActualEndTime.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {

        showDialog(mTvActualEndTime.getText().toString().trim(), R.string.chooseTime,
            REQUEST_ACTUAL_DATE_END);
      }
    });

    if (mMenuType == CHECK) {
      mEtReason.setEnabled(false);
      mTvActualStartTime.setEnabled(false);
      mTvActualEndTime.setEnabled(false);
      mEtActualHours.setEnabled(false);
    }
  }

  private void initData() {
    if (mcontent != null) {
      mId = mcontent.getId();
      mEtReason.setText(mcontent.getOvertimeReason());
      mTvActualStartTime.setText(mcontent.getActSTime());
      mTvActualEndTime.setText(mcontent.getActETime());
      mEtActualHours.setText(mcontent.getActWorkNum());
    } else {
      mId = UUID.randomUUID().toString();
      mEtActualHours.setText("0.0");
    }
  }

  private void showDialog(String startDate, int titleId, int requestCode) {

    Date date = DateUtil.stringToDate(startDate);
    if (null == date) {
      date = new Date();
    }
    FragmentManager fm = getActivity().getSupportFragmentManager();
    DialogFragment dialog = BaseTimeDialogFragment.newInstance(date, titleId);
    dialog.setTargetFragment(CheckOverNewFragment.this, requestCode);
    dialog.show(fm, "");
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) return;
    String startDate;// 开始时间
    String endDate;// 结束时间

    if (requestCode == REQUEST_ACTUAL_DATE_START) {
      Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);

      String dateString = DateUtil.dateToString(resultData);

      mTvActualStartTime.setText(dateString);
      startDate = mTvActualStartTime.getText().toString().trim();
      endDate = mTvActualEndTime.getText().toString().trim();
      // 获取工时
      getWorkHours(requestCode, startDate, endDate);
    }
    if (requestCode == REQUEST_ACTUAL_DATE_END) {
      Date resultData = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);

      String dateString = DateUtil.dateToString(resultData);

      mTvActualEndTime.setText(dateString);
      startDate = mTvActualStartTime.getText().toString().trim();
      endDate = mTvActualEndTime.getText().toString().trim();
      // 获取工时
      getWorkHours(requestCode, startDate, endDate);
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  public boolean isCorrectInput() {
    // 验证文本信息
    String reasonString = mEtReason.getText().toString().trim();
    String actualBeginTime = mTvActualStartTime.getText().toString().trim();
    String actualEndTime = mTvActualEndTime.getText().toString().trim();
    String planHours = mEtActualHours.getText().toString().trim();
    if (TextUtils.isEmpty(reasonString)) {
      ToastUtil.show(R.string.no_content);
      return false;
    }
    if (TextUtils.isEmpty(actualBeginTime)) {
      ToastUtil.show(R.string.chooseRealStartTime);
      return false;
    }
    if (TextUtils.isEmpty(actualEndTime)) {
      ToastUtil.show(R.string.chooseRealEndTime);
      return false;
    }
    if (TextUtils.isEmpty(planHours)) {
      ToastUtil.show(R.string.no_outover_hours);
      return false;
    }
    if (!DateUtil.before(actualBeginTime, actualEndTime)) {
      ToastUtil.show(R.string.realEndTimeAfterRealStartTime);
      return false;
    }

    return true;
  }

  private void volleyPostSave() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_OVERSUB_SAVE);
    HashMap<String, String> params = new HashMap<>();
    params.put("pid", mPid);
    params.put("id", mId);
    params.put("overtimeReason", mEtReason.getText().toString());
    params.put("actSTime", mTvActualStartTime.getText().toString());
    params.put("actETime", mTvActualEndTime.getText().toString());
    params.put("actWorkNum", mEtActualHours.getText().toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getVolleyResponce());
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_OVERSUB_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, getVolleyResponce());
  }

  private VolleyResponse getVolleyResponce() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();
          switch (successType) {
            case "1":
              ToastUtil.show(R.string.success_operation);
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
              break;
            case "0":
              ToastUtil.show(successsMessage.getMessage());
              break;
            default:
              ToastUtil.show(R.string.failure_operation);
              break;
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }
    };
  }

  private void getWorkHours(final int requestCode, String startTime, String endTime) {

    if (TextUtils.isEmpty(startTime) || TextUtils.isEmpty(endTime)) {
      return;
    }
    if (DateUtil.before(endTime, startTime)) {
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_OVER_WORKHOUR);
    HashMap<String, String> params = new HashMap<>();
    params.put("sTime", startTime);
    params.put("eTime", endTime);
    MyUtils.showDialogLoading(getActivity(), R.string.loadingWorkHour);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {
        MyUtils.dismissDialog();
        try {
          SuccessMessage successMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          if (successMessage.getResult().equals(SuccessMessage.SUCCESS)) {
            String message = successMessage.getMessage();

            if (requestCode == REQUEST_ACTUAL_DATE_START
                || requestCode == REQUEST_ACTUAL_DATE_END) {
              mEtActualHours.setText(message);
            }
          }
        } catch (Exception e) {
          LogUtil.e("workTimeOverError=" + e, e);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        MyUtils.dismissDialog();
      }
    });
  }

  public static CheckOverNewFragment newInstance(CheckOverListOriginal.CheckOverListContent content,
      String dataStatus, String pid) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    args.putSerializable(EXTRA_STATUS, dataStatus);
    args.putSerializable(EXTRA_PID, pid);
    CheckOverNewFragment fragment = new CheckOverNewFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
